package com.zzq.demo.tio.server.handler;

import com.zzq.demo.tio.common.AbsAioHandler;
import com.zzq.demo.tio.common.HelloPacket;
import com.zzq.demo.tio.common.Type;
import com.zzq.demo.tio.common.bs.AbsBsHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.tio.common.starter.annotation.TioServerMsgHandler;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : zhaoziqian
 * @description :
 * @date : 2019/10/24 10:41
 */
@Slf4j
@Qualifier
@TioServerMsgHandler
public class HelloServerAioHandler extends AbsAioHandler {

    private static Map<Byte, AbsBsHandler<?>> handlerMap = new HashMap<>();

    static {
        handlerMap.put(Type.SIMPLE_REQ, new SimpleMsgReqHandler());
        handlerMap.put(Type.HEART_BEAT_REQ, new HeartbeatReqHandler());
    }

    /**
     * 处理消息
     *
     * @param packet
     * @param channelContext
     * @throws Exception
     */
    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        HelloPacket helloPacket = (HelloPacket) packet;
        Byte type = helloPacket.getType();
        AbsBsHandler<?> bsHandler = handlerMap.get(type);
        if (bsHandler == null) {
            log.error("{}, 找不到处理类，type:{}", channelContext, type);
            return;
        }
        bsHandler.handler(helloPacket, channelContext);
    }
}
